<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body style="background-color: aqua">
    <div><input type="text" id="input" /> <button id="send">发送</button></div>
    <div class="list"></div>
    <script>
      window.addEventListener('message', onMessage);
      let port = null;
      function onMessage(e) {
        if (!e.ports.length) return;
        const { data } = e.data;
        if (!port) {
          port = e.ports[0];
        }
        const list = document.querySelector('.list');
        e.ports[0].postMessage('这是子页面发送的数据');
        e.ports[0].onmessage = (e) => {
          list.innerHTML += `<p>${e.data}</p>`;
        };
      }
      document.querySelector('#send').addEventListener('click', () => {
        const input = document.querySelector('#input');
        const message = input.value;
        if (!port) return;
        port.postMessage(message);
      });
    </script>
  </body>
</html>
